<?php
include('checkLogin.php');
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>教师管理</title>
    <link rel="stylesheet" href="bootstrap/bootstrap.css">
    <!--[if IE]>
    <![endif]-->

</head>
<body style="background: #414057;">
<div class=".container">
    <!-- Modal -->
    <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-header">
            <h3 id="myModalLabel">提示</h3>
        </div>
        <div class="modal-body">
            <p>努力加载中…</p>
        </div>
    </div>
    <div id="bulletinModal" class="modal hide fade" style="width: 80%;" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-header">
            <h3 id="myModalLabel">公告栏</h3>
        </div>
        <div class="modal-body">
            <table class="table table-striped" id="bulletinTable">

            </table>
        </div>
        <div class="modal-footer">
            <a href="javascript:void(0);" onclick="newBulletin()" class="btn btn-primary">新建</a>
            <a href="#" class="btn" data-dismiss="modal" aria-hidden="true">关闭</a>
        </div>
    </div>
    <div id="newBulletinModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h3 id="myModalLabel">新建公告</h3>
        </div>
        <div class="modal-body">
            <fieldset>
                <label>标题</label>
                <div class="alert" id="alertTitleEmpty" style="display: none;">
                    <strong>标题不得为空！</strong>
                </div>
                <div class="alert" id="alertTitleExceed" style="display: none;">
                    <strong>标题最多20字！</strong>
                </div>
                <input style="width: 97%;" type="text" placeholder="不超过20字" name="btitle" id="btitle">
                <label>内容</label>
                <div class="alert" id="alertContentEmpty" style="display: none;">
                    <strong>内容不得为空！</strong>
                </div>
                <div class="alert" id="alertContentExceed" style="display: none;">
                    <strong>内容最多100字！</strong>
                </div>
                <textarea style="width: 97%;" rows="5" name="bcontent" id="bcontent" placeholder="不超过100字"></textarea>
                <div class="alert" id="alertReleaseBulletinError" style="display: none;">
                    啊呦，出错了：
                </div>
            </fieldset>
        </div>
        <div class="modal-footer">
            <a href="javascript:void(0);" onclick="releaseNewBulletin()" class="btn">提交</a>
        </div>
    </div>
    <div id="sharedFileModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-header">
            <h3 id="myModalLabel">文件</h3>
        </div>
        <div class="modal-body">
            <div class="input-append pull-right">
                <form id="uploadFileForm" enctype="multipart/form-data">
                    <input class="span3 uneditable-input" id="uploadFile" type="text" disabled>
                    <input type="file" style="display: none;"
                           onchange="document.getElementById('uploadFile').value=this.value.substring(this.value.lastIndexOf('\\')+1);"
                           id="file" name="file">
                    <button class="btn" type="button" onclick="selectFile()">选择...</button>
                    <button class="btn btn-success" type="button" id="btnClickToUpload" onclick="checkFileAndUpload()">上传</button>
                </form>
            </div>
            <table class="table table-striped" id="fileTable">
            </table>
        </div>
        <div class="modal-footer">
            <a href="#" class="btn" data-dismiss="modal" aria-hidden="true">关闭</a>
        </div>
    </div>
    <div id="studentAssignModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-header">
            <h3 id="myModalLabel">设置管理员</h3>
        </div>
        <div class="modal-body">
            <table class="table table-striped" id="studentTable">

            </table>
        </div>
        <div class="modal-footer">
            <a href="#" class="btn" data-dismiss="modal" aria-hidden="true">关闭</a>
        </div>
    </div>
    <!-- Content -->
    <div class="navbar">
        <div class="navbar-inner">
            <a class="brand" href="#">超级课程表（教师端）</a>
            <ul class="nav">
                <li class="active"><a href="#">课程管理</a></li>
            </ul>
            <form class="navbar-form pull-right">
                <a class="btn"><?php echo $real_name; ?></a>
                <button type="button" class="btn btn-danger" onclick="logout()">退出</button>
            </form>
        </div>


    </div>
    <center>
        <div class="well" style="width: 80%;">
            <div class="row">

                <center>
                    <div class="text-info">您教授的课程</div>
                </center>
                <center>
                    <table class="table table-bordered" style="width: 90%;">
                        <thead>
                        <tr>
                            <th>#</th>
                            <th>课程ID</th>
                            <th>课程名</th>
                            <th>地点</th>
                            <th>人数</th>
                            <th>签到</th>
                            <th>管理</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        $mysqli = new mysqli("127.0.0.1", "root", "1258", "daowei");
                        $sql = "SELECT course_id, course_name, location, faceset_token, count(id) AS stu_count FROM course " .
                            "NATURAL JOIN teaches NATURAL JOIN takes WHERE t_id='" . $_SESSION['username'] . "' GROUP BY course_id, course_name, location, faceset_token";
                        $mysqli->query("set names 'utf8'");
                        $result = $mysqli->query($sql);
                        $i = 0;
                        while ($resultLine = mysqli_fetch_assoc($result)) {
                            $i++;
                            echo "<tr><td>$i</td>" .
                                "<td>" . $resultLine['course_id'] . "</td>" .
                                "<td>" . $resultLine['course_name'] . "</td>" .
                                "<td>" . $resultLine['location'] . "</td>" .
                                "<td><a href='javascript:void(0);' onclick=\"manageStu('" . $resultLine['course_id'] . "')\">" . $resultLine['stu_count'] . "</a></td>" .
                                "<center><td><button class='btn' onclick='checkIn(this.id)' id='checkin_" . $resultLine['course_id'] . "'>签到</button>";
                            if ($resultLine['faceset_token'] == "") {
                                echo "<button class='btn' onclick='turnOnFaceset(this.id)' name='open' id='faceset_" . $resultLine['course_id'] . "'>开启人脸识别签到</button>";
                            } else {
                                echo "<button class='btn' onclick='turnOffFaceset(this.id)' name='close' id='faceset_" . $resultLine['course_id'] . "'>关闭人脸识别签到</button>";
                            }
                            echo "</td></center><center><td><div class=\"dropdown\">
  <button class=\"btn\" data-toggle=\"dropdown\">管理班级 <b class=\"caret\"></b></button>
  <ul class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\"dLabel\">
    <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"0\" href=\"viewAttendance.php?course_id=" . $resultLine['course_id'] . "&course_name=" . $resultLine['course_name'] . "\">签到情况</a></li>
    <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"1\" href=\"javascript:void(0);\" onclick=\"bulletin('" . $resultLine['course_id'] . "')\">发布公告</a></li>
    <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"2\" href=\"javascript:void(0);\" onclick=\"uploadFile('" . $resultLine['course_id'] . "')\">资料上传</a></li>
  </ul>
</div></td></center>";
                        }
                        ?>
                        </tbody>
                    </table>
                </center>
            </div>
        </div>
    </center>
</div>


<script src="bootstrap/jquery-3.2.0.min.js"></script>
<script src="bootstrap/bootstrap.js"></script>
<script type="text/javascript">
    window.sel_courseId = '';
    function logout() {
        location.href = 'logout.php';
    }
    function checkIn(id) {
        id = id.substring(id.indexOf("_") + 1);
        post("checkIn.php", {id: id})
    }

    function selectFile() {
        $('#file').trigger("click");
    }

    function uploadFile(courseId) {
        window.sel_courseId = courseId;
        getFileList(courseId);
        $('#sharedFileModal').modal({
            backdrop: 'static',
            keyboard: false
        });
    }

    function checkFileAndUpload() {
        var fileNameInput = $('#uploadFile');
        var buttonUpload = $('#btnClickToUpload');
        if (buttonUpload.attr('class') === 'btn btn-success disabled') return;
        if (window.sel_courseId === '') {
            alert('异常：无法获取课程号，请联系管理员');
            return;
        }
        if (fileNameInput.val() === '') {
            alert('请选择文件');
            return;
        }
        var formData = new FormData();
        formData.append('file', $('#file')[0].files[0]);
        formData.append('course_id', window.sel_courseId);
        buttonUpload.attr('class', 'btn btn-success disabled');
        $.ajax({
            cache: false,
            type: "POST",
            url:'fileUpload.php',
            data:formData,
            async: true,
            processData: false,
            contentType: false,
            error: function(request) {
                alert('上传失败！原因：网络异常');
                buttonUpload.attr('class', 'btn btn-success');
            },
            success: function(data) {
                buttonUpload.attr('class', 'btn btn-success');
                if (data === 'success') {
                    getFileList(window.sel_courseId);
                    alert('上传成功！');

                } else {
                    alert('上传失败！原因：' + data);
                    console.log(data);
                }
            }
        });
    }

    function getFileList(courseId) {
        if (typeof courseId === 'undefined') {
            courseId = window.sel_courseId;
        } else {
            window.sel_courseId = courseId;
        }
        $.ajax({
            cache: false,
            type: "GET",
            url: 'getFileList.php?course_id=' + courseId,
            async: true,
            error: function () {
                alert('网络异常');
            },
            success: function (data) {
                document.getElementById("fileTable").innerHTML = data;
            }
        });
    }

    function removeFile(fId) {
        $.ajax({
            cache: false,
            type: "GET",
            url: 'removeFile.php?course_id=' + window.sel_courseId + "&f_id=" + fId,
            async: true,
            error: function () {
                alert('网络异常');
            },
            success: function (data) {
                if (data === 'success') {
                    getFileList();
                } else {
                    alert('删除失败，原因：' + data);
                }
            }
        });
    }

    function turnOnFaceset(id) {
        if (document.getElementById(id).innerHTML === "关闭人脸识别签到") {
            turnOffFaceset(id);
            return;
        }
        $('#myModal').modal({
            backdrop: 'static',
            keyboard: false
        });
        id = id.substring(id.indexOf("_") + 1);
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "../face/turnOnFaceset.php?course_id=" + id, true);
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                $('#myModal').modal('hide');
                if (xmlhttp.responseText == "success") {
                    document.getElementById("faceset_" + id).innerHTML = "关闭人脸识别签到";
                } else {
                    alert("开启失败： " + xmlhttp.responseText);
                }
            }
        };
        xmlhttp.send();
    }

    function turnOffFaceset(id) {
        if (document.getElementById(id).innerHTML == "开启人脸识别签到") {
            turnOnFaceset(id);
            return;
        }
        $('#myModal').modal({
            backdrop: 'static',
            keyboard: false
        });
        id = id.substring(id.indexOf("_") + 1);

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "../face/turnOffFaceset.php?course_id=" + id, true);
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                $('#myModal').modal('hide');
                if (xmlhttp.responseText == "success") {
                    document.getElementById("faceset_" + id).innerHTML = "开启人脸识别签到";
                } else {
                    alert("关闭失败： " + xmlhttp.responseText);
                }
            }
        };
        xmlhttp.send();
    }

    function manageStu(course_id) {
        window.sel_courseId = course_id;
        document.getElementById("studentTable").innerHTML = "";
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "getStudentInClass.php?course_id=" + course_id, true);
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("studentTable").innerHTML = xmlhttp.responseText;
                $('#studentAssignModal').modal({
                    backdrop: 'static',
                    keyboard: false
                });
            }
        };
        xmlhttp.send();

    }

    function bulletin(course_id) {
        sel_courseId = course_id;
        document.getElementById("bulletinTable").innerHTML = "";
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "getBulletin.php?course_id=" + course_id, true);
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("bulletinTable").innerHTML = xmlhttp.responseText;
                $('#bulletinModal').modal({
                    backdrop: 'static',
                    keyboard: false
                }).css({
                    width: '80%', 'margin-left': function () {
                        return -($(this).width() / 2);
                    }
                });
            }
        };
        xmlhttp.send();
    }

    function newBulletin() {
        $('#btitle').val('');
        $('#bcontent').val('');
        $('#bulletinModal').modal('hide');
        $('#newBulletinModal').modal({
            backdrop: 'static',
            keyboard: false
        });
    }

    function releaseNewBulletin() {
        $('#alertTitleEmpty').css('display', 'none');
        $('#alertTitleExceed').css('display', 'none');
        $('#alertContentEmpty').css('display', 'none');
        $('#alertContentExceed').css('display', 'none');
        $('#alertReleaseBulletinError').css('display', 'none');
        var title = $('#btitle').val();
        var content = $('#bcontent').val();
        var valid = true;
        if (title === '') {
            $('#alertTitleEmpty').css('display', 'block');
            valid = false;
        } else if (title.length > 20) {
            valid = false;
            $('#alertTitleExceed').css('display', 'block');
        }
        if (content === '') {
            valid = false;
            $('#alertContentEmpty').css('display', 'block');
        } else if (title.length > 20) {
            valid = false;
            $('#alertContentExceed').css('display', 'block');
        }
        if (valid) {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open("POST", "releaseBulletin.php", true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                    if (xmlhttp.responseText == 'success') {
                        $('#newBulletinModal').modal('hide');
                        bulletin(sel_courseId);
                    } else {
                        $('#alertReleaseBulletinError').html('啊呦，出错了：' + xmlhttp.responseText);
                        $('#alertReleaseBulletinError').css('display', 'block');
                    }
                }
            };
            xmlhttp.send("course_id=" + sel_courseId + "&author=-1&title=" + title + "&content=" + content);
        }
    }

    function deleteBulletin(b_id) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "deleteBulletin.php?course_id=" + sel_courseId + "&b_id=" + b_id, true);
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                if (xmlhttp.responseText == 'success') {
                    bulletin(sel_courseId);
                } else {
                    alert('删除失败：' + xmlhttp.responseText);
                }
            }
        };
        xmlhttp.send();
    }

    function post(URL, PARAMS) {
        var temp = document.createElement("form");
        temp.action = URL;
        temp.method = "post";
        temp.target = "_blank";
        temp.style.display = "none";
        for (var x in PARAMS) {
            var opt = document.createElement("textarea");
            opt.name = x;
            opt.value = PARAMS[x];
            // alert(opt.name)
            temp.appendChild(opt);
        }
        document.body.appendChild(temp);
        temp.submit();
        return temp;
    }

    function addPriority(stu_id) {
        if ($('#assis_' + stu_id).attr('class') == 'btn btn-success') {
            return;
        }
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "changePriority.php?course_id=" + sel_courseId + "&stu_id=" + stu_id + "&type=add", true);
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                if (xmlhttp.responseText == 'success') {
                    $('#assis_' + stu_id).attr('class', 'btn btn-success');
                    $('#ord_' + stu_id).attr('class', 'btn');
                }
            }
        };
        xmlhttp.send();
    }

    function removePriority(stu_id) {
        if ($('#ord_' + stu_id).attr('class') == 'btn btn-success') {
            return;
        }
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "changePriority.php?course_id=" + sel_courseId + "&stu_id=" + stu_id + "&type=remove", true);
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                if (xmlhttp.responseText == 'success') {
                    $('#assis_' + stu_id).attr('class', 'btn');
                    $('#ord_' + stu_id).attr('class', 'btn btn-success');
                }
            }
        };
        xmlhttp.send();
    }
</script>
</body>
</html>